<template>
  <a-card title="店员管理" class="general-card" :bordered="false">
    <searchTable
      :columns="columnsSearch"
      @reset="
        (val) => {
          apiParams = { ...apiParams, ...val };
        }
      "
      @search="
        (val) => {
          apiParams = { ...apiParams, ...val };
        }
      "
    ></searchTable>

    <a-row style="margin-bottom: 16px">
      <a-col :span="16">
        <a-space>
          <a-button type="primary" @click="handleAdd"> 添加 </a-button>
          <a-button @click="resetPass"> 重置密码 </a-button>
          <a-button type="primary" status="danger" @click="delAll">
            批量删除
          </a-button>
        </a-space>
      </a-col>
    </a-row>
    <tablePage
      ref="tablePageRef"
      :columns="columnsTable"
      :methods="sortMethods"
      :api="getUserListData"
      :api-params="apiParams"
      :checkbox="true"
      :bordered="true"
      @selectTableChange="selectTableChange"
    >
      <template #avatar="{ data }">
        <a-avatar>
          <img alt="avatar" :src="data.avatar" />
        </a-avatar>
      </template>
      <template #shopkeeper="{ data }">
        <a-badge v-if="data.shopkeeper" color="green" text="是"> </a-badge>
        <a-badge v-else color="red" text="否"> </a-badge>
      </template>
      <template #isSuper="{ data }">
        <a-badge v-if="data.isSuper" color="green" text="是"> </a-badge>
        <a-badge v-else color="red" text="否"> </a-badge>
      </template>
      <template #status="{ data }">
        <a-badge v-if="data.status" color="green" text="启用"> </a-badge>
        <a-badge v-else color="red" text="禁用"> </a-badge>
      </template>

      <template #forbidden="{ data }">
        <a-button
          v-if="data.status"
          type="text"
          status="danger"
          @click="handleForbidden(data)"
          >禁用
        </a-button>
        <a-button
          v-else
          type="text"
          status="success"
          @click="handleEnable(data)"
        >
          启用
        </a-button>
      </template>
      <template #editor="{ data }">
        <a-button type="text" status="warning" @click="handleEdit(data)">
          编辑
        </a-button>
      </template>
      <template #remove="{ data }">
        <a-button type="text" status="danger" @click="handleRemove(data)">
          删除
        </a-button>
      </template>
    </tablePage>
    <!-- 添加modal -->
    <a-modal
      v-model:visible="enableAddModal"
      :align-center="false"
      ok-text="提交"
      @ok="submitUser"
    >
      <template #title> {{ modalTitle }}</template>
      <a-form ref="formRef" :model="memberData">
        <a-form-item
          field="mobile"
          label="手机号"
          :rules="[REQUIRED, VARCHAR20]"
          :validate-trigger="['change']"
        >
          <a-input v-model="memberData.mobile" @change="checkClerks" />
          &nbsp;<a-button v-if="!memberCheck" @click="onCheckClerk"
            >校验</a-button
          >
          &nbsp;<a-button v-if="memberCheck" @click="checkAgainClerk"
            >重新校验</a-button
          >
        </a-form-item>
        <a-form-item
          v-if="newMember"
          field="username"
          label="用户名"
          :rules="[REQUIRED, VARCHAR20]"
          :validate-trigger="['change']"
        >
          <a-input v-model="memberData.username" />
        </a-form-item>
        <a-form-item
          v-if="oldMember"
          field="username"
          label="用户名"
          :rules="[REQUIRED, VARCHAR20]"
          :validate-trigger="['change']"
        >
          <a-input v-model="memberData.username" disabled />
        </a-form-item>
        <a-form-item
          v-if="newMember"
          field="password"
          label="密码"
          :rules="[REQUIRED, VARCHAR20]"
          :validate-trigger="['change']"
        >
          <a-input-password v-model="memberData.password" />
        </a-form-item>
        <a-form-item
          v-if="newMember || oldMember"
          field="isSuper"
          label="超级管理员"
          :rules="[REQUIRED, VARCHAR20]"
          :validate-trigger="['change']"
        >
          <a-radio-group v-model="memberData.isSuper" type="button">
            <a-radio :value="1">是</a-radio>
            <a-radio :value="0">否</a-radio>
          </a-radio-group>
          <!-- <a-input v-model="memberData.value.form.email" /> -->
        </a-form-item>
        <a-form-item
          v-if="(oldMember || newMember) && memberData.isSuper == 0"
          field="roles"
          label="选择角色"
        >
          <a-select v-model="memberData.roles" placeholder="选择角色" multiple>
            <a-option
              v-for="item in roleList"
              :key="item.id"
              :value="item.id"
              >{{ item.name }}</a-option
            >
          </a-select>
        </a-form-item>
        <a-form-item
          v-if="oldMember || newMember"
          field="departmentTitle"
          label="所属部门"
        >
          <a-tree-select
            v-model:model-value="memberData.departmentId"
            :field-names="{ children: 'children', title: 'title', key: 'id' }"
            :allow-search="true"
            :allow-clear="true"
            :data="dataDep"
            placeholder="选择所属部门"
            :filter-tree-node="filterTreeNode"
          ></a-tree-select>
        </a-form-item>
      </a-form>
    </a-modal>
    <!-- 编辑modal -->
    <a-modal
      v-model:visible="userEditModalVisible"
      :align-center="false"
      ok-text="提交"
      @ok="updateSubmit"
    >
      <template #title> {{ modalTitle }}</template>
      <a-form ref="formRef" :model="editForm">
        <a-form-item
          field="mobile"
          label="手机号"
          :validate-trigger="['change']"
        >
          <a-input v-model="mobile" disabled />
        </a-form-item>
        <a-form-item
          field="clerkName"
          label="店员名称"
          :validate-trigger="['change']"
        >
          <a-input v-model="clerkName" disabled />
        </a-form-item>
        <a-form-item
          field="isSuper"
          label="超级管理员"
          :rules="[REQUIRED, VARCHAR20]"
          :validate-trigger="['change']"
        >
          <a-radio-group v-model="editForm.isSuper" type="button">
            <a-radio :value="1">是</a-radio>
            <a-radio :value="0">否</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          v-if="editForm.isSuper == 0"
          field="roles"
          label="选择角色"
        >
          <a-select v-model="editForm.roles" placeholder="选择角色" multiple>
            <a-option
              v-for="item in roleList"
              :key="item.id"
              :value="item.id"
              >{{ item.name }}</a-option
            >
          </a-select>
        </a-form-item>
        <a-form-item field="departmentId" label="所属部门">
          <a-tree-select
            v-model:model-value="editForm.departmentId"
            :field-names="{ children: 'children', title: 'title', key: 'id' }"
            :allow-search="true"
            :allow-clear="true"
            :data="dataDep"
            placeholder="选择所属部门"
            :filter-tree-node="filterTreeNode"
          ></a-tree-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script setup lang="ts">
  import searchTable from '@/components/search-column/index.vue';
  import tablePage from '@/components/table-pages/index.vue';
  import { VARCHAR255, REQUIRED, VARCHAR20, MOBILE } from '@/utils/validator';
  import { SearchRule, MethodsRule, ColumnsDataRule } from '@/types/global';
  import {
    getRoleList,
    getUserListData,
    addUser,
    editOtherUser,
    disableUser,
    deleteUser,
    resetUserPass,
    initDepartment,
    checkClerk,
    getClerk,
  } from '@/api/shops';
  import { ref, reactive, onMounted } from 'vue';
  import { FormInstance } from '@arco-design/web-vue/es/form';
  import useCurrentInstance from '@/hooks/useCurrentInstance';
  import { Message } from '@arco-design/web-vue';
  import { md5 } from '@/utils/md5';

  const tablePageRef = ref<any>();
  const roleList = ref<Array<any>>([]); // 角色列表
  const dataDep = ref([]); // 部门列表
  const modalTitle = ref<string>(''); // 弹框标题
  const modalType = ref(0); // 新增编辑标识
  const formRef = ref<FormInstance>();
  const userEditModalVisible = ref(false); // 用户编辑模态框
  const selectList = ref([]); // 接收子组件传过来的值
  const ids = ref<string>(''); // 多选行id
  const open = ref(0);
  const newMember = ref(false);
  const oldMember = ref(false);
  const memberCheck = ref(false);
  const editForm = ref({
    // 表单
    id: '',
    isSuper: 0,
    roles: [],
    departmentId: '',
    departmentTitle: '',
  });
  const mobile = ref('');
  const clerkName = ref('');
  //  获取modal
  const modal = useCurrentInstance().globalProperties?.$modal;
  const columnsSearch: Array<SearchRule> = [
    {
      label: '店员名称',
      model: 'clerkName',
      disabled: false,
      input: true,
    },

    {
      label: '联系方式',
      model: 'mobile',
      disabled: false,
      input: true,
    },
  ];

  const columnsTable: any = [
    {
      title: '店员名称',
      dataIndex: 'clerkName',
    },
    {
      title: '手机号码',
      dataIndex: 'mobile',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '店主',
      dataIndex: 'shopkeeper',
      slot: true,
      slotTemplate: 'shopkeeper',
    },
    {
      title: '超级管理员',
      dataIndex: 'isSuper',
      slot: true,
      slotTemplate: 'isSuper',
    },
    {
      title: '状态',
      dataIndex: 'status',
      slot: true,
      slotTemplate: 'status',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
  ];

  const sortMethods: MethodsRule = {
    title: '操作',
    width: 300,
    fixed: 'right',
    methods: [
      {
        title: '编辑',
        callback: 'editor',
        slot: true,
        slotTemplate: 'editor',
      },
      {
        title: '禁用',
        callback: 'forbidden',
        slot: true,
        slotTemplate: 'forbidden',
      },
      {
        title: '删除',
        callback: 'remove',
        slot: true,
        slotTemplate: 'remove',
      },
    ],
  };
  const enableAddModal = ref(false);
  const fid = ref('');
  const memberData = ref<any>({
    mobile: '',
    username: '',
    password: '',
    roles: [],
    departmentTitle: '',
    departmentId: '',
    isSuper: 0,
    id: '',
  });
  // 选择的行
  const selectTableChange = (val: any) => {
    selectList.value = val;
  };
  // 点击添加
  function handleAdd() {
    modalType.value = 0;
    modalTitle.value = '添加店员';
    fid.value = '';
    Object.keys(memberData.value).forEach((key) => {
      memberData.value[key] = '';
    });
    oldMember.value = false;
    newMember.value = false;
    enableAddModal.value = true;
  }
  // 删除用户
  const handleRemove = (val: any) => {
    modal.confirm({
      title: '确认删除',
      content: '您确认要删除此店员',
      alignCenter: false,
      onOk: async () => {
        const res = await deleteUser(val.id);
        if (res.data.success) {
          Message.success('删除成功');
          tablePageRef.value.init();
        }
      },
    });
  };
  // 编辑用户
  function handleEdit(val: any) {
    getClerk(val.id).then((res) => {
      mobile.value = res.data.result.mobile;
      clerkName.value = res.data.result.clerkName;
      editForm.value.isSuper = 0;
      editForm.value.id = res.data.result.id;
      if (res.data.result.isSuper) {
        editForm.value.isSuper = 1;
      }
      editForm.value.departmentId = res.data.result.departmentId;
      const selectRolesId = [] as any;
      if (res.data.result.roles) {
        res.data.result.roles.forEach((item: any) => {
          selectRolesId.push(item.id);
        });
      }
      editForm.value.roles = selectRolesId;
      modalTitle.value = '修改店员';
      userEditModalVisible.value = true;
    });
  }
  // 编辑提交
  const updateSubmit = () => {
    if (editForm.value.roles)
      editForm.value.roles = editForm.value.roles.filter((item: any) => !!item);

    editOtherUser(editForm.value.id, editForm.value).then((res) => {
      if (res.data.success) {
        Message.success('操作成功');
        tablePageRef.value.init();
        userEditModalVisible.value = false;
      }
    });
  };
  // 回调禁用
  function handleForbidden(data: any) {
    const params = {
      status: false,
    };
    modal.confirm({
      title: '确认禁用',
      content: '您确认要禁用此店员',
      alignCenter: false,
      onOk: async () => {
        const res = await disableUser(data.id, params);
        if (res.data.success) {
          Message.success('禁用成功');
          tablePageRef.value.init();
        }
      },
    });
  }
  // 回调启用
  function handleEnable(data: any) {
    const params = {
      status: true,
    };
    modal.confirm({
      title: '确认启用',
      content: '您确认要启用此店员',
      alignCenter: false,
      onOk: async () => {
        const res = await disableUser(data.id, params);
        if (res.data.success) {
          Message.success('操作成功');
          tablePageRef.value.init();
        }
      },
    });
  }
  const apiParams = ref({
    disabled: 'OPEN',
  });
  // 重置密码
  const resetPass = () => {
    if (selectList.value.length <= 0) {
      Message.error('请选中数据后重试');
      return;
    }
    ids.value = '';
    selectList.value.forEach((item: any) => {
      ids.value += `${item.id},`;
    });
    const joinid = ids.value.substring(0, ids.value.length - 1);
    modal.confirm({
      title: '确认重置',
      content: `您确认要重置所选的${selectList.value.length}条店员数据密码为【123456】?`,
      alignCenter: false,
      onOk: async () => {
        const res = await resetUserPass(joinid);
        if (res.data.success) {
          Message.success('删除成功');
          tablePageRef.value.init();
        }
      },
    });
  };
  // 批量删除
  const delAll = () => {
    if (selectList.value.length <= 0) {
      Message.error('您还未选择要删除的数据');
      return;
    }
    ids.value = '';
    selectList.value.forEach((item: any) => {
      ids.value += `${item.id},`;
    });
    const joinid = ids.value.substring(0, ids.value.length - 1);
    modal.confirm({
      title: '确认删除',
      content: `您确认要删除所选的${selectList.value.length}条数据?`,
      alignCenter: false,
      onOk: async () => {
        const res = await deleteUser(joinid);
        if (res.data.success) {
          Message.success('删除成功');
          tablePageRef.value.init();
        }
      },
    });
  };
  // 获取角色列表
  const getRoleLists = () => {
    getRoleList({ pageNumber: 1, pageSize: 10000 }).then((res) => {
      if (res.data.success) {
        roleList.value = res.data.result.records;
      }
    });
  };
  // 获取部门数据
  const initDepartmentData = () => {
    initDepartment().then((res) => {
      if (res.data.success) {
        dataDep.value = res.data.result;
      }
    });
  };

  const filterTreeNode = (searchValue: any, nodeData: any) => {
    return nodeData.title.toLowerCase().indexOf(searchValue.toLowerCase()) > -1;
  };
  // 确认提交
  const submitUser = () => {
    // 添加用户 避免编辑后传入id
    const params = JSON.parse(JSON.stringify(memberData.value));
    delete params.id;
    delete params.status;
    if (newMember.value) {
      if (params.password == '' || params.password == undefined) {
        Message.error('密码不能为空');
      }
      if (params.password.length < 6) {
        Message.error('密码长度不得少于6位');
      }
      params.password = md5(params.password);
    } else {
      params.password = memberData.value.password;
    }

    if (params.roles)
      params.roles = params.roles.filter((item: any) => !!item);
    addUser(params).then((res) => {
      if (res.data.success) {
        Message.success('操作成功');
        tablePageRef.value.init();
        enableAddModal.value = false;
      }
    });
  };
  // 重新校验会员
  const checkAgainClerk = () => {
    memberCheck.value = false;
    newMember.value = false;
    oldMember.value = false;
  };
  // 检测当前店员
  const onCheckClerk = () => {
    if (memberData.value.mobile) {
      newMember.value = false;
      oldMember.value = false;
      checkClerk(memberData.value.mobile).then((res) => {
        if (!res.data.result.id) {
          newMember.value = true;
        } else {
          oldMember.value = true;
          memberData.value.username = res.data.result.username;
          memberData.value.password = res.data.result.password;
        }
        memberData.value.isSuper = 1;
        memberCheck.value = true;
      });
    }
  };
  const checkClerks = () => {
    open.value = memberData.value.mobile.length;
    if (open.value == 11) {
      onCheckClerk();
    }
    if (open.value < 11) {
      checkAgainClerk();
    }
  };
  // 初始化
  onMounted(() => {
    getRoleLists();
    initDepartmentData();
  });
</script>
